package com.example.day12_7_12_1.base;


import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public abstract class BaseRlvAdapter<T> extends RecyclerView.Adapter<BaseRlvAdapter.BaseViewHolder> {
    private Context mContext;
    private List<T> mList;

    public BaseRlvAdapter(Context context, List<T> list) {
        mContext = context;
        mList = list;
    }
    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(mContext).inflate(getLayout(), parent, false);
        return new BaseViewHolder(inflate);
    }

    protected abstract int getLayout();
    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
        T t = mList.get(position);
        bindData(holder, t);
    }

    protected abstract void bindData(BaseViewHolder holder, T t);

    public void addData(List<T> list) {
        if (list != null && list.size() > 0) {
            mList.addAll(list);
            notifyDataSetChanged();
        }
    }

    public void updateData(List<T> list) {
        if (list != null && list.size() > 0) {
            mList.clear();
            mList.addAll(list);
            notifyDataSetChanged();
        }
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public static class BaseViewHolder extends RecyclerView.ViewHolder {

        SparseArray<View> mMap = new SparseArray<>();

        public BaseViewHolder(View itemView) {
            super(itemView);
        }

        public View findView(@IdRes int id) {
            View view = mMap.get(id);
            if (view == null) {
                view = itemView.findViewById(id);
                mMap.put(id,view);
            }

            return view;
        }

        public void setText(@IdRes int id, String text){

            try {
                TextView view = (TextView) findView(id);
                view.setText(text);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
